import React, {useEffect, useState} from 'react';
import './Background.css';
import HomePage from './pages/HomePage';
import {PropagateLoader} from 'react-spinners';
import {useDispatch, useSelector} from "react-redux";
import {setUser, setIsLogin} from "./store/modules/userStore";
import instance from "./utils/axiosUtil";
import Login from "./components/Login";
import {message} from "antd";

function App() {
    const {isLogin} = useSelector(state => state.user)
    const [authChecking, setAuthChecking] = useState(false);
    const dispatch = useDispatch();
    //整个程序数据的初始化 这里必须是阻塞 要等所有数据初始化完成才能开始使用
    useEffect(() => {
        setAuthChecking(true);
        //当前用户信息(先尝试自动登录逻辑)
        const autoLogin = async ()=>{
            await instance.post('http://localhost:5532/auth/autoLogin').then(res => {
                if (res.data.code === 1) { //自动登录成功
                    dispatch(setUser(res.data.data));
                    dispatch(setIsLogin(true));
                    message.success('登录成功');
                }
            }).then(res => {
                setAuthChecking(false);
                return res;
            })
        }
        autoLogin();
    }, [dispatch])


    return (
        authChecking ?
            <div className="loading-container">
                <div className="loading-spinner"> {/* 添加加载动画 */}
                    <PropagateLoader color={'#007bff'} loading={true} size={15}/>
                </div>
            </div>
            :
            <div className="App background" style={{overflowY:'auto'}}>
                {isLogin ? <HomePage/> : <Login/>}
            </div>
    );
}

export default App;
